import {
  build
} from './build';
import {
  isCli
} from '@core/util';
import {
  PROFILE_DIR,
  logInfo,
  logSuccess
} from '@shared';

const chokidar = require('chokidar');

const cli = isCli();
let routesPath = '*(pages|platforms)/**/*.json';
let profilePath = PROFILE_DIR + '/*.json';

if (cli) {
  routesPath = 'src/' + routesPath;
  profilePath = 'src/' + profilePath;
}

export function watch(options) {
  const watcher = chokidar.watch([routesPath, profilePath]);
  let isReady = false;

  watcher.on('ready', () => {
      isReady = true;
      logInfo('watcher is ready, waiting for changes...');
      build(options);
    })
    .on('add', (path) => {
      if (isReady) {
        logSuccess('add [' + path + ']');
        build(options);
      }
    })
    .on('change', (path) => {
      if (isReady) {
        logSuccess('change [' + path + ']');
        build(options);
      }
    })
    .on('unlink', (path) => {
      if (isReady) {
        logSuccess('unlink [' + path + ']');
        build(options);
      }
    });

  return watcher;
}
